package ar.com.tallerdos.smartdinner.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import ar.com.tallerdos.smartdinner.model.Subrubro;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class SubrubrosLista extends ListActivity {
    public final static String SUBRUBRO_SELECCIONADO = "ar.com.tallerdos.smartdinner.activity.SubrubrosLista.SUBRUBRO_SELECCIONADO";

    private List<Subrubro> subrubros = new ArrayList<Subrubro>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	Intent intent = getIntent();

	String subrubrosJson = intent
		.getStringExtra(RubrosLista.RUBRO_SELECCIONADO);
	Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
		.create();

	subrubros = gson.fromJson(subrubrosJson,
		new TypeToken<List<Subrubro>>() {
		}.getType());

	this.setListAdapter(new ArrayAdapter<Subrubro>(this,
		android.R.layout.simple_list_item_1, subrubros));
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
	Intent intent = new Intent(this, ProductosLista.class);

	Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
		.create();
	String productosJson = gson.toJson(subrubros.get(position)
		.getProductos());

	intent.putExtra(SUBRUBRO_SELECCIONADO, productosJson);
	startActivityForResult(intent, 1);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	if (requestCode == 1) {

	    if (resultCode == RESULT_OK) {
		Intent returnIntent = new Intent();
		returnIntent.putExtra("result", data.getIntExtra("result", 0));
		setResult(RESULT_OK, returnIntent);
		finish();
	    }
	    if (resultCode == RESULT_CANCELED) {
		// Write your code if there's no result
	    }
	}
	finish();
    }
}
